<template>
  <div 
    v-if="hasSelection" 
    class="toolbar" 
    ref="toolbarRef"
    :style="toolbarStyle"
  >
  <div class="toolbar-handle" @mousedown="startDrag">
      ⠿ 拖拽移动
    </div>

    <div class="toolbar-section">
      <h3>属性设置</h3>
      
      <div v-if="selectedTypes.includes('text')" class="text-properties">
        <div class="toolbar-item">
          <label>内容:</label>
          <input 
            type="text" 
            v-model="selectedContent" 
            @input="updateSelectedElementsOptimized('content', selectedContent)"
            @focus="disableGlobalKeys"
            @blur="enableGlobalKeys"
          >
        </div>

        <div class="toolbar-row">
          <div class="toolbar-item">
            <label>字号:</label>
            <input 
              type="number" 
              min="12" 
              v-model="selectedFontSize" 
              @input="updateSelectedElementsOptimized('fontSize', selectedFontSize)"
              @focus="disableGlobalKeys"
              @blur="enableGlobalKeys"
            >
          </div>
          <div class="toolbar-item">
            <label>字体:</label>
            <select 
              v-model="selectedFontFamily" 
              @change="updateSelectedElementsOptimized('fontFamily', selectedFontFamily)"
              style="width: 100px; height: 30px;"
            >
              <option value="Arial">Arial</option>
              <option value="Times New Roman">Times New Roman</option>
              <option value="SimSun">宋体</option>
              <option value="Microsoft YaHei">微软雅黑</option>
              <option value="SimHei">黑体</option>
            </select>
          </div>
        </div>
        
        <div class="toolbar-item">
            <label>颜色:</label>
            <input 
              type="color" 
              v-model="selectedTextColor" 
              @input="updateSelectedElementsOptimized('color', selectedTextColor)"
            >
        </div>

        <div class="toolbar-item style-buttons">
          <button 
            :class="{ active: selectedBold }" 
            @click="updateSelectedElementsOptimized('bold', !selectedBold)"
            title="加粗 (Ctrl+B)"
          >
            B
          </button>
          <button 
            :class="{ active: selectedItalic }" 
            @click="updateSelectedElementsOptimized('italic', !selectedItalic)"
            title="斜体 (Ctrl+I)"
          >
          <span style="display:inline-block; transform: skewX(-12deg); font-family: Arial;">
    I
  </span>
          </button>
          <button 
            :class="{ active: selectedUnderline }" 
            @click="updateSelectedElementsOptimized('underline', !selectedUnderline)"
            title="下划线 (Ctrl+U)"
          >
            U
          </button>
          <button 
            :class="{ active: selectedStrikethrough }" 
            @click="updateSelectedElementsOptimized('strikethrough', !selectedStrikethrough)"
            title="删除线"
            style="text-decoration: line-through;"
          >
            S
          </button>
        </div>
        
        <div class="toolbar-item style-buttons">
           <button :class="{ active: selectedTextAlign === 'left' }" @click="updateSelectedElementsOptimized('textAlign', 'left')">左</button>
           <button :class="{ active: selectedTextAlign === 'center' }" @click="updateSelectedElementsOptimized('textAlign', 'center')">中</button>
           <button :class="{ active: selectedTextAlign === 'right' }" @click="updateSelectedElementsOptimized('textAlign', 'right')">右</button>
        </div>
        
        <hr class="divider">
      </div>

      <div class="toolbar-item">
        <label>背景色:</label>
        <div style="display: flex; gap: 5px; align-items: center;">
          <input 
            type="color" 
            v-model="displayBackgroundColor"
          >
          <button 
            @click="setBackgroundTransparent"
            class="small-btn"
            :class="{ active: selectedBackground === 'transparent' }"
            title="设为透明"
          >
            透明
          </button>
        </div>
      </div>
      
      <div class="toolbar-item">
        <label>边框色:</label>
        <input 
          type="color" 
          v-model="selectedBorderColor" 
          @input="updateSelectedElementsOptimized('borderColor', selectedBorderColor)"
        >
        <span class="color-value">{{ selectedBorderColor }}</span>
      </div>
      
      <div class="toolbar-item">
        <label>边框宽度:</label>
        <input 
          type="range" 
          min="0" 
          max="10" 
          v-model="selectedBorderWidth" 
         @input="updateSelectedElementsOptimized('borderWidth', parseInt(selectedBorderWidth.toString()))"
        >
        <span>{{ selectedBorderWidth }}px</span>
      </div>

      <div class="toolbar-item" v-if="selectedTypes.includes('image')">
        <label>滤镜:</label>
        <select v-model="selectedFilter"
        @input="updateSelectedElementsOptimized('filter', ($event.target as HTMLSelectElement).value)">
        <option value="无滤镜">无滤镜</option>
        <option value="灰度">灰度</option>
        <option value="复古">复古</option>
        <option value="反色">反色</option>
        <option value="提亮">提亮</option>
        <option value="高对比">高对比</option>
        <option value="高饱和">高饱和</option>
        <option value="去饱和">去饱和</option>
        <option value="色相180°">色相180°</option>
        <option value="模糊">模糊</option>
      </select>
      </div>
      
      <div class="toolbar-item" v-if="showImageProperties">
        <label>透明度:</label>
          <input
            type="range"
            min="0"
            max="1"
            step="0.05"
            :value="selectedOpacity"
            @input="onOpacityInput"
          >
        <span>{{ Math.round(selectedOpacity * 100) }}%</span>
      </div>  
      
      <div class="toolbar-actions" v-if="showImageProperties">
        <button class="reset-btn" @click="resetImageSize">重置尺寸</button>
    </div>

      <div class="toolbar-row">
        <div class="toolbar-item">
          <label>X:</label>
          <input 
            type="number" 
            v-model="selectedX" 
            @input="updateSelectedElementsOptimized('x', parseInt(selectedX.toString()) || 0)"
            @focus="disableGlobalKeys"
            @blur="enableGlobalKeys"
            ref="xInput"
          >
        </div>
        <div class="toolbar-item">
          <label>Y:</label>
          <input 
            type="number" 
            v-model="selectedY" 
            @input="updateSelectedElementsOptimized('y', parseInt(selectedY.toString()) || 0)"
            @focus="disableGlobalKeys"
            @blur="enableGlobalKeys"
            ref="yInput"
          >
        </div>
      </div>
      
      <div class="toolbar-row">
        <div class="toolbar-item">
          <label>宽度:</label>
          <input 
            type="number" 
            min="10" 
            v-model="selectedWidth" 
            @input="updateSelectedElementsOptimized('width', Math.max(1, parseInt(selectedWidth.toString()) || 100))"
            @focus="disableGlobalKeys"
            @blur="enableGlobalKeys"
            ref="widthInput"
          >
        </div>
        <div class="toolbar-item">
          <label>高度:</label>
          <input 
            type="number" 
            min="10" 
            v-model="selectedHeight" 
            @input="updateSelectedElementsOptimized('height', Math.max(1, parseInt(selectedHeight.toString()) || 100))"
            @focus="disableGlobalKeys"
            @blur="enableGlobalKeys"
            ref="heightInput"
          >
        </div>
      </div>
      
      <div class="toolbar-actions">
        <button @click="copySelected" class="copy-btn" :disabled="!hasSelection">
          复制 (Ctrl+C)
        </button>
        <button @click="pasteElements" class="paste-btn" :disabled="!canPaste">
          粘贴 (Ctrl+V)
        </button>
        <button @click="deleteSelected" class="delete-btn">
          删除
        </button>
        <button @click="clearSelection" class="clear-btn">
          取消
        </button>
      </div>
      
      <div class="selection-info">
        <p>已选中 {{ selectedCount }} 个元素</p>
        <p v-if="selectedTypes.length > 0">类型: {{ selectedTypes.join(', ') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted } from 'vue';
import { useCanvasStore } from '../stores/canvas';
import type { TextElement } from '../types/canvas';

// 防抖和节流函数
const debounce = <T extends (...args: any[]) => void>(func: T, delay: number) => {
  let timeoutId: ReturnType<typeof setTimeout>;
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
};
const throttle = <T extends (...args: any[]) => void>(func: T, limit: number) => {
  let inThrottle: boolean;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

const canvasStore = useCanvasStore();
const toolbarRef = ref<HTMLElement>();

// 图片专属表单数据 
const selectedOpacity = ref<number>(1);
const selectedFilter = ref(''); 

// 输入框引用
const xInput = ref<HTMLInputElement>();
const yInput = ref<HTMLInputElement>();
const widthInput = ref<HTMLInputElement>();
const heightInput = ref<HTMLInputElement>();

const isDragging = ref(false);
const dragOffset = ref({ x: 0, y: 0 });

const loadToolbarPosition = () => {
  const saved = localStorage.getItem('toolbar-position');
  if (saved) return JSON.parse(saved);
  return { x: 20, y: 80 };
};
const saveToolbarPosition = (position: { x: number; y: number }) => {
  localStorage.setItem('toolbar-position', JSON.stringify(position));
};
const toolbarPosition = ref(loadToolbarPosition());

const globalKeysEnabled = ref(true);

const toolbarStyle = computed(() => ({
  left: `${toolbarPosition.value.x}px`,
  top: `${toolbarPosition.value.y}px`
}));

// 计算属性
const hasSelection = computed(() => canvasStore.selectedElements().length > 0);
const selectedCount = computed(() => canvasStore.selectedElements().length);
const selectedElements = computed(() => canvasStore.selectedElements());
const canPaste = computed(() => canvasStore.clipboard.length > 0);
const selectedTypes = computed(() => [...new Set(selectedElements.value.map(el => el.type))]);
const showImageProperties = computed(() => selectedElements.value.some((el: { type: string }) => el.type === 'image'));

// 表单数据
const selectedBackground = ref('#ffffff');
const selectedBorderColor = ref('#000000');
const selectedBorderWidth = ref(0);
const selectedX = ref(0);
const selectedY = ref(0);
const selectedWidth = ref(100);
const selectedHeight = ref(100);

// 文本专属数据
const selectedContent = ref('');
const selectedFontSize = ref(16);
const selectedFontFamily = ref('Arial');
const selectedTextColor = ref('#000000');
const selectedBold = ref(false);
const selectedItalic = ref(false);
const selectedUnderline = ref(false);
const selectedStrikethrough = ref(false);
const selectedTextAlign = ref('left');

// 计算属性：解决背景色输入框不支持 transparent 的问题
const displayBackgroundColor = computed({
  get: () => {
    return selectedBackground.value === 'transparent' ? '#ffffff' : selectedBackground.value;
  },
  set: (val) => {
    selectedBackground.value = val;
    updateSelectedElementsOptimized('background', val);
  }
});

// 方法定义
const disableGlobalKeys = () => { globalKeysEnabled.value = false; };
const enableGlobalKeys = () => { globalKeysEnabled.value = true; };

const onOpacityInput = (e: Event) => {
  const val = parseFloat((e.target as HTMLInputElement).value);
  selectedOpacity.value = val;
  updateSelectedElementsOptimized('opacity', val);
};

const resetImageSize = () => {
  const img = canvasStore.selectedElements().find((el: { type: string }) => el.type === 'image');
  if (!img) return;
  const w = (img as any).initialWidth || (img as any).width || 200;
  const h = (img as any).initialHeight || (img as any).height || 200;
  updateSelectedElements('width', w); 
  updateSelectedElements('height', h);
  selectedWidth.value = w;
  selectedHeight.value = h;
};

// 拖拽逻辑
const startDrag = (event: MouseEvent) => {
  event.preventDefault();
  isDragging.value = true;
  if (toolbarRef.value) {
    const rect = toolbarRef.value.getBoundingClientRect();
    dragOffset.value = { x: event.clientX - rect.left, y: event.clientY - rect.top };
  }
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
};

const handleDrag = (event: MouseEvent) => {
  if (!isDragging.value) return;
  const newX = event.clientX - dragOffset.value.x;
  const newY = event.clientY - dragOffset.value.y;
  const maxX = window.innerWidth - 300;
  const maxY = window.innerHeight - 400;
  toolbarPosition.value = { x: Math.max(0, Math.min(newX, maxX)), y: Math.max(0, Math.min(newY, maxY)) };
};

const stopDrag = () => {
  isDragging.value = false;
  saveToolbarPosition(toolbarPosition.value);
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const handleResize = () => {
  const maxX = window.innerWidth - 300;
  const maxY = window.innerHeight - 400;
  if (toolbarPosition.value.x > maxX || toolbarPosition.value.y > maxY) {
    toolbarPosition.value = { x: Math.min(toolbarPosition.value.x, maxX), y: Math.min(toolbarPosition.value.y, maxY) };
    saveToolbarPosition(toolbarPosition.value);
  }
};

// 监听选中元素变化
watch(selectedElements, (newElements) => {
  const img = newElements.find((el: { type: string }) => el.type === 'image');
  selectedFilter.value = img ? (img.filter ?? '无滤镜') : '无滤镜';
  selectedOpacity.value = img ? (img.opacity ?? 1) : 1;

  if (newElements.length) {
    const firstElement = newElements[0];
    selectedBackground.value = firstElement.background ?? '#ffffff';
    selectedBorderColor.value = firstElement.borderColor ?? '#000000';
    selectedBorderWidth.value = firstElement.borderWidth ?? 0;
    selectedX.value = firstElement.x;
    selectedY.value = firstElement.y;
    selectedWidth.value = firstElement.width;
    selectedHeight.value = firstElement.height;

    if (newElements.length === 1 && firstElement.type === 'text') {
      const textEl = firstElement as TextElement;
      selectedContent.value = textEl.content || '';
      selectedFontSize.value = textEl.fontSize || 16;
      selectedFontFamily.value = textEl.fontFamily || 'Arial';
      selectedTextColor.value = textEl.color || '#000000';
      selectedBold.value = textEl.bold || false;
      selectedItalic.value = textEl.italic || false;
      selectedUnderline.value = textEl.underline || false;
      selectedStrikethrough.value = textEl.strikethrough || false;
      selectedTextAlign.value = textEl.textAlign || 'left';
    }
  } else {
    selectedBackground.value = '#ffffff';
    selectedBorderColor.value = '#000000';
    selectedBorderWidth.value = 0;
    selectedX.value = 0;
    selectedY.value = 0;
    selectedWidth.value = 0;
    selectedHeight.value = 0;
  }
}, { immediate: true, deep: true });

// 更新方法
const updateSelectedElements = (property: string, value: any) => {
  if (property === 'filter' && value === '') value = '无滤镜';
  if (property === 'width' || property === 'height') {
    const minSize = 10;
    value = Math.max(minSize, parseInt(value) || minSize);
    if (property === 'width') selectedWidth.value = value;
    else if (property === 'height') selectedHeight.value = value;
  }
  
  const selectedIds = canvasStore.selectedElements().map(el => el.id);
  selectedIds.forEach(id => {
    canvasStore.updateElement(id, { [property]: value });
  });
};

const setBackgroundTransparent = () => {
  selectedBackground.value = 'transparent';
  updateSelectedElementsOptimized('background', 'transparent');
};

// 核心修复函数：处理字体大小类型转换
const updateSelectedElementsOptimized = (property: string, value: any) => {
  if (property === 'background' && value !== 'transparent') {
    selectedBackground.value = value;
  }

  // ✨✨ 核心修复：字号必须转为数字 ✨✨
  if (property === 'fontSize') {
    const size = parseInt(String(value));
    if (isNaN(size) || size < 10) return;
    debounceUpdate(property, size);
    return;
  }

  // ✨✨ 核心修复：边框宽度必须转为数字 ✨✨
  if (property === 'borderWidth') {
    const width = parseInt(String(value));
    if (isNaN(width) || width < 0) return;
    throttleUpdate(property, width);
    return;
  }

  if (['opacity'].includes(property)) throttleUpdate(property, value);
  else if (['x', 'y', 'width', 'height'].includes(property)) debounceUpdate(property, value);
  else immediateUpdate(property, value);
};

const immediateUpdate = (property: string, value: any) => updateSelectedElements(property, value);
const throttleUpdate = throttle((property: string, value: any) => updateSelectedElements(property, value), 50);
const debounceUpdate = debounce((property: string, value: any) => updateSelectedElements(property, value), 100);

const deleteSelected = () => canvasStore.deleteSelectedElements();
const clearSelection = () => canvasStore.clearSelection();
const copySelected = () => canvasStore.copySelectedElements();
const pasteElements = () => canvasStore.pasteElements();

onMounted(() => window.addEventListener('resize', handleResize));
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.toolbar {
  position: fixed;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  min-width: 280px;
  z-index: 1000;
  cursor: default;
  user-select: none;
}
.toolbar-handle {
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  cursor: grab;
  font-size: 14px;
  color: #666;
  border-radius: 8px 8px 8px 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.toolbar-handle::before { font-size: 16px; margin-right: 8px; }
.toolbar-handle:active { cursor: grabbing; background: #dee2e6; }
.toolbar-section { padding: 16px; }
.toolbar-section h3 { margin: 0 0 16px 0; font-size: 16px; border-bottom: 1px solid #eee; padding-bottom: 8px; }
.toolbar-item { display: flex; align-items: center; margin-bottom: 12px; gap: 8px; }
.toolbar-item label { min-width: 80px; font-size: 14px; color: #666; }
.toolbar-item input[type="color"] { width: 40px; height: 30px; border: 1px solid #ddd; cursor: pointer; }
.toolbar-item input[type="range"] { flex: 1; }
.toolbar-item input[type="number"], .toolbar-item input[type="text"] { width: 70px; padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; }
.toolbar-row { display: flex; gap: 12px; }
.toolbar-actions { display: flex; gap: 8px; margin-top: 16px; padding-top: 16px; border-top: 1px solid #eee; transform: translateY(0); }
.toolbar-actions button { flex: 1; padding: 8px; border: none; border-radius: 4px; cursor: pointer; color: white; margin-bottom: 8px; }
.delete-btn { background: #e74c3c; }
.copy-btn { background: #3498db; }
.paste-btn { background: #2ecc71; }
.clear-btn { background: #95a5a6; }
.reset-btn { background: #f39c12 !important; }
.reset-btn:hover, .reset-btn:active { background: #e67e22 !important; }
.selection-info { margin-top: 12px; font-size: 12px; color: #666; border-top: 1px solid #eee; padding-top: 8px; }

/* 文本样式按钮 */
.style-buttons { display: flex; gap: 4px; }
.style-buttons button { flex: 1; padding: 6px; background: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-weight: bold; color: #333; }
.style-buttons button.active { background: #4a90e2; color: white; border-color: #357abd; }
.divider { border: 0; border-top: 1px solid #eee; margin: 12px 0; }
.small-btn { padding: 2px 6px; font-size: 12px; background: #f1f1f1; border: 1px solid #ccc; border-radius: 4px; cursor: pointer; }
.small-btn.active { background: #e0e0e0; color: #999; border-style: dashed; }
</style>